<template lang="pug">
  .clearfix
    Modal(
      width="450"
      v-model="isShowChangeDifferentModal"
      class-name="vertical-center-modal"
      footer-hide
    )
      .clearfix
        .text-center.mt-20.mb-20.font-14
          |请问是否要对已选中的员工进行
          span.text-error.font-weight.font-16.pl-5.pr-5 {{changeDifferentTitleStr}}减少
          |的操作
        //- Row.font-14.mb-20(v-if="changeDifferentAction !== 'addDifferent'")
        //-   Col.text-right.line-h-36.pr-10.mb-20(span="9") 减少申报时间：
        //-   Col.mb-20(span="15")
        //-     DatePicker.w-100(type="date" v-model="differentTime" clearable)
        //-   Col.text-right.line-h-36.pr-10(span="9") 减少备注：
        //-   Col(span="15")
        //-     Input.w-100(type="text" v-model="differentTime" clearable)
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="150")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.label") {{c_item.label}}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" type="date")
        .text-center.pb-10
          Button.ml-10.mr-10(@click="cancel(changeDifferentAction)") 关闭
          Button.ml-10.mr-10(type="primary" @click="ok(changeDifferentAction, true)" :loading="!isCanSubmit") 确认
    Modal(
      width="650"
      v-model="isShowSelectSecurityModal"
      class-name="vertical-center-modal"
      footer-hide
    )
      .h500.overflow-y-scroll
        .mb-10.bg-blue-light.pall-10 按保险编号分类选择
        .clearfix.font-14.mb-20.pb-10.pl-10.pr-10
          CheckboxGroup(v-model="currentClassifySecurityArr" @on-change="classifySecurityChange")
            Checkbox.mb-10.mr-20(v-for="(c_item, idx) of classifySecurityArr" :key="idx" :label="c_item.securityGUID") {{c_item.securityNO}}
        
        .bg-blue-light.mb-10.pall-10
          Checkbox(:indeterminate="indeterminate" :value="isCheckAll" @click.prevent.native="handleCheckAll")
            |全选所有{{changeDifferentTitleStr}}
        
        .clearfix.font-14.mb-20.pb-10.pl-10.pr-10.border-b-dashed(v-for="(item, index) of allSecurityArr" :key="index")
          .mb-10.text-error {{item.EmployeeName}}的{{changeDifferentTitleStr}}
          Checkbox.mb-10(:indeterminate="item.indeterminate" :value="item.isCheckAll" @click.prevent.native="handleCheckItemAll(item.EmployeeGUID)") 全选
          CheckboxGroup.ivu-row(v-model="item.isSelectArr" @on-change="selectSecurityChange(item.EmployeeGUID, index)")
            Checkbox.ivu-col-span-10.mb-10(v-for="(c_item, idx) of item.EmployeeSelectArr" :key="idx" :label="c_item.securityGUID") {{c_item.securityNO}}
      .text-center.pb-10
        Button.ml-10.mr-10(type="primary" @click="ok2(changeDifferentAction, saveParamDetails, true)" :loading="!isCanSubmit") 确认
    Modal(
      width="650"
      v-model="isShowCheckTreatmentEnjoy"
      class-name="vertical-center-modal"
      title="提示"
      okText='保存'
      @on-ok="ok3()"
      @on-cancel="cancel"
    )
      p.font-16.mb-30.mt-30.ml-20.mr-20 {{errorMessage}}
</template>

<script>
import { ChangesApi } from '@/api/Changes.api.js'
import { SysBasedataApi } from '@/api/SysBasedata.api.js'
import { Common } from '@/utils/common.js'
export default {
  name: '',

  props: {
    changeDifferentTitleId: {
      type: String,
      default: ''
    },
    changeDifferentTitleStr: {
      type: String,
      default: ''
    },
    changeDifferentAction: {
      type: String,
      default: ''
    }
    // selectedEmployeeArr: {
    //   type: Array,
    //   default () {
    //     return []
    //   }
    // }
  },

  data () {
    return {
      isShowChangeDifferentModal: false,
      isShowCheckTreatmentEnjoy: false,
      isShowSelectSecurityModal: false, // 选择员工商保/社保/公积金
      // isShowSelectShebaoModal: false, // 选择员工社保
      // isShowSelectGongjijinModal: false, // 选择员工公积金
      selectedEmployeeArr: [],
      differentTime: 1,
      allSecurityArr: [], // 所有保险列表
      social: [],
      saveParamDetails: [], // 保存时的参数
      indeterminate: false,
      isCheckAll: false, // 所有保险是否全选
      classifySecurityArr: [], // 保险分类
      currentClassifySecurityArr: [],
      isCanSubmit: true,
      formData: {
        reduceChangeTime: new Date(),
        leaveReason: null,
        description: null
      },
      formItem: [
        { type: 'datePicker', label: '减少申报时间：', placeholder: '请选择减少申报时间', prop: 'reduceChangeTime', model: 'reduceChangeTime', style: 'ivu-col-span-24' },
        { type: 'select', label: '离职原因：', placeholder: '请选择离职原因', prop: 'leaveReason', model: 'leaveReason', style: 'ivu-col-span-24', options: 'LeaveReason' },
        { type: 'input', label: '减少备注：', placeholder: '请输入减少备注', prop: 'description', model: 'description', style: 'ivu-col-span-24' },
      ],
      rules: {
        reduceChangeTime: [
          { required: true, message: '请选择减少申报时间', type: 'date', trigger: 'change' }
        ],
        leaveReason: [
          { required: true, message: '请选择离职原因', trigger: 'change' }
        ],
      },
      arrListDown: {
        LeaveReason: []
      },
      confirmType: null,
      errorMessage: ''
    }
  },

  watch: {
  },

  mounted () {
    this.getLeaveReasonList()
  },

  methods: {
    ok (changeDifferentAction, type) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          this.isShowChangeDifferentModal = false
          this.save(changeDifferentAction, null, type, 'ok')
        }
      })
      // if (this.formData.reduceChangeTime) {
      //   this.isCanSubmit = false
      //   this.isShowChangeDifferentModal = false
      //   this.save(changeDifferentAction)
      // } else {
      //   this.$Message.warning('请选择减少申报时间')
      // }
    },
    ok2 (changeDifferentAction, saveParamDetails, type) {
      this.isCanSubmit = false
      this.isShowSelectSecurityModal = false
      this.save(changeDifferentAction, saveParamDetails, type, 'ok2')
      this.$emit('query')
    },
    ok3 () {
      console.log(this.confirmType)
      if(this.confirmType =='ok'){
        this.ok(this.changeDifferentAction, false)
      }
      if(this.confirmType =='ok2'){
        this.ok2(this.changeDifferentAction, this.saveParamDetails, false)
      }
    },
    cancel () {
      this.isShowChangeDifferentModal = false
      this.isShowCheckTreatmentEnjoy = false
    },

    show () {
      this.isCanSubmit = true
      this.isShowChangeDifferentModal = true
      this.classifySecurityArr = []
      this.currentClassifySecurityArr = []
    },

    async getLeaveReasonList () {
      let res = await SysBasedataApi.getLeaveReasonList({type: 'LeaveReason'})
      if (res.data.success) {
        this.arrListDown.LeaveReason = res.data.data.map(item => {
          if (item.isSelect) {
            this.formData.leaveReason = item.text
          }
          return { label: item.text, value: item.value, isSelect: item.isSelect }
        })
      }
    },
    // 数据字典
    // getEnum () {
    //   let typeName = 'LeaveReason'
    //   Common.getLeaveReasonList(typeName, this.arrListDown)
    // },

    // 保存异动信息
    async save (changeDifferentAction, saveParamDetails, checkTreatmentEnjoy, type) {
      var tempDetails = []
      var tempObjArr = []
      this.selectedEmployeeArr.map(item => {
        console.log('🐟 item: ', item)
        tempDetails.push({ EmployeeGUID: item.id, SecurityGUIDs: '' })
        tempObjArr.push({ EmployeeGUID: item.id, EmployeeName: item.name, EmployeeSelectArr: [], isSelectArr: [], isCheckAll: false, indeterminate: false })
      })
      // this.saveParamDetails = tempDetails
      if (!saveParamDetails) {
        this.saveParamDetails = tempDetails
      } else {
        this.saveParamDetails = saveParamDetails
      }

      var params = {
        ChangeType: changeDifferentAction === 'addDifferent' ? 1 : 2, // 异动类型(1新增、2减少)
        ChangeSecurityType: this.changeDifferentTitleId, // 异动申报参保类型
        ReduceChangeTime: this.formData.reduceChangeTime, // 异动减少申报时间
        LeaveReason: this.formData.leaveReason,
        Description: this.formData.description,
        Details: this.saveParamDetails,
        CheckTreatmentEnjoy: checkTreatmentEnjoy
      }
      let res = await ChangesApi.save(params)
      if (res.status === 200 && res.data.success) {
        // this.$Message.success(res.data.message)
        this.$Message.success({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      } else {
        if (res.data.code === 'SelectSecurityGUID' && res.data.data.length > 0) {
          let result = res.data.data
          this.isShowSelectSecurityModal = true
          this.isCanSubmit = true
          for (var i of result) {
            // console.log('⭐ i: ', i)
            tempObjArr.map((item, index) => {
              // console.log('🆗 item: ', item)
              if (i.employeeGUID.toLowerCase().replace(/[-]/g, '') === item.EmployeeGUID.toLowerCase().replace(/[-]/g, '')) {
                item.EmployeeSelectArr.push(i)
              }
            })
          }
          this.allSecurityArr = tempObjArr

          this.classifySecurityArr = Common.ToHeavy2(this.classifySecurityArr.concat(result), 'securityGUID')
          console.log('🌈 result: ', result)
          console.log('🌈 this.classifySecurityArr: ', this.classifySecurityArr)
        } else if ( res.data.code === 'CheckSecurityHasTreatmentEnjoy' ) {
          this.isShowCheckTreatmentEnjoy = true
          this.confirmType = type
          this.errorMessage = res.data.message
          return
        } else {
          // this.$Message.error({
          //   content: res.data.message,
          //   duration: 0,
          //   closable: true
          // })
        }
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 单个员工的保险选择改变
    selectSecurityChange (EmployeeGUID, index) {
      this.saveParamDetails.map(item => {
        if (EmployeeGUID === item.EmployeeGUID) {
          var selectItem = this.allSecurityArr[index]
          item.SecurityGUIDs = selectItem.isSelectArr.join(',')
        
          if (selectItem.EmployeeSelectArr.length === selectItem.isSelectArr.length) { // 全选
            selectItem.isCheckAll = true
            selectItem.indeterminate = false

            this.isCheckAll = true
            this.indeterminate = false
          } else {
            selectItem.isCheckAll = false
            selectItem.indeterminate = false

            this.isCheckAll = false
            this.indeterminate = false
          } 

          // 点击单个的员工社保时，修改分类多选里的状态及样式
          this.currentClassifySecurityArr = []
        }
      })
    },

    // 点击保险分类的多选框
    classifySecurityChange () {
      this.allSecurityArr.map(item => {
        var arr = []
        item.EmployeeSelectArr.map((c_item, c_index) => {
          if (this.currentClassifySecurityArr.indexOf(c_item.securityGUID) !== -1) {
            arr.push(c_item.securityGUID)
          }
        })
        item.isSelectArr = arr

        if (item.EmployeeSelectArr.length === item.isSelectArr.length) {
          item.isCheckAll = true
          item.indeterminate = false
        } else {
          item.isCheckAll = false
          item.indeterminate = false
        }
      })

      if (this.currentClassifySecurityArr.length === this.classifySecurityArr.length) {
        this.isCheckAll = true
        this.indeterminate = false
      } else {        
        this.isCheckAll = false
        this.indeterminate = false
      }

      this.saveParamDetails.map(paramDetailItem => {
        if (this.currentClassifySecurityArr.indexOf(paramDetailItem.EmployeeGUID) !== 0) {
          var tempCurrentSecurity = this.allSecurityArr.find(item => {
            return paramDetailItem.EmployeeGUID === item.EmployeeGUID
          })
          paramDetailItem.SecurityGUIDs = tempCurrentSecurity.isSelectArr.join(',')
        }
      })

      console.log('this.allSecurityArr: ', this.allSecurityArr)
      console.log('this.saveParamDetails: ', this.saveParamDetails)
    },

    // 每个人下面的保险是否全选
    handleCheckItemAll (employeeGUID) {
      var selectItem = {}
      var selectItemIndex
      this.allSecurityArr.map((item, index) => {
        if (item.EmployeeGUID === employeeGUID) {
          selectItem = item
          selectItemIndex = index
        }
      })
      var selectCheckboxArr = []
      selectItem.EmployeeSelectArr.map(c_item => {
        selectCheckboxArr.push(c_item.securityGUID)
      })
      // console.log('🐟 全选数组为 ', selectCheckboxArr)

      if (selectItem.indeterminate) {
        selectItem.isCheckAll = false
      } else {
        selectItem.isCheckAll = !selectItem.isCheckAll
      }
      selectItem.indeterminate = false

      if (selectItem.isCheckAll) {
        selectItem.isSelectArr = selectCheckboxArr
        selectItem.indeterminate = false
      } else {
        selectItem.isSelectArr = []
        selectItem.indeterminate = false
      }

      // selectItem.isSelectArr = selectCheckboxArr
      this.allSecurityArr[selectItemIndex] = selectItem

      this.saveParamDetails.map(item => {
        if (item.EmployeeGUID === selectItem.EmployeeGUID) {
          item.SecurityGUIDs = selectItem.isSelectArr.join(',')
        }
      })
      console.log('🐟 this.allSecurityArr: ', this.allSecurityArr)
      console.log('⭐ this.saveParamDetails: ', this.saveParamDetails)
    },

    // 所有保险是否全选
    handleCheckAll () {
      if (this.indeterminate) {
        this.isCheckAll = false
      } else {
        this.isCheckAll = !this.isCheckAll
      }
      this.indeterminate = false

      if (this.isCheckAll) {
        this.allSecurityArr.map(item => {
          item.EmployeeSelectArr.map(c_item => {
            item.isSelectArr.push(c_item.securityGUID)
          })
          this.indeterminate = false
          item.isCheckAll = true
          item.indeterminate = false

          this.saveParamDetails.map(paramDetailItem => {
            if (paramDetailItem.EmployeeGUID === item.EmployeeGUID) {
              paramDetailItem.SecurityGUIDs = item.isSelectArr.join(',')
            }
          })
        })

        var tempCurrentClassifySecurityArr = []
        this.classifySecurityArr.map(item => {
          tempCurrentClassifySecurityArr.push(item.securityGUID)
        })
        this.currentClassifySecurityArr = tempCurrentClassifySecurityArr
      } else {
        this.allSecurityArr.map(item => {
          item.isSelectArr = []
          this.indeterminate = false
          item.isCheckAll = false
          item.indeterminate = false
          this.currentClassifySecurityArr = []

          this.saveParamDetails.map(paramDetailItem => {
            paramDetailItem.SecurityGUIDs = ''
          })
        })
      }

      console.log('this.saveParamDetails: ', this.saveParamDetails)
    }
  }
}
</script>

<style lang="less" scope>

</style>
